{% extends "base.html" %}

{% block title %}SimpleTrade - 完整评估结果{% endblock %}

{% block extra_css %}
    <style>
        /* 筛选区域样式 */
        .filter-container {
            background: #f8f9fa;
            padding: 15px 20px;
            border-radius: 8px;
            margin: 20px 0;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: center;
        }
        .filter-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .filter-group label {
            font-weight: 600;
            color: #34495e;
        }
        select, input[type="checkbox"] {
            padding: 6px 10px;
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            font-size: 14px;
        }
        input[type="checkbox"] {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

        /* 表格样式 */
        .result-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        .result-table th,
        .result-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ecf0f1;
        }
        .result-table th {
            background: #3498db;
            color: white;
            font-weight: 600;
            cursor: pointer;
            position: relative;
        }
        .result-table th:hover {
            background: #2980b9;
        }
        /* 核心修改1：表格行 hover 样式（提示可点击）+ 鼠标指针 */
        .result-table tr {
            cursor: pointer; /* 整行鼠标变指针 */
        }
        .result-table tr:hover {
            background: #e8f4fd; /* hover时浅蓝背景，比原来的f8f9fa更明显 */
        }

        /* 排序指示和状态样式 */
        .sort-indicator {
            margin-left: 5px;
            font-size: 12px;
            opacity: 0.8;
        }
        .buy-yes { color: #27ae60; font-weight: 600; }
        .buy-no { color: #7f8c8d; }
        .empty-state {
            text-align: center;
            padding: 50px 0;
            color: #7f8c8d;
            font-style: italic;
            cursor: default !important; /* 空状态行取消指针 */
        }
        .empty-state:hover {
            background: transparent !important; /* 空状态行取消hover背景 */
        }
        /* 按钮样式 */
        .eval-btn {
            padding: 8px 15px;
            background-color: #40BA8D;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .eval-btn:disabled {
            background-color: #bdc3c7;
            color: #7f8c8d;
            cursor: not-allowed;
            opacity: 0.9;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .filter-container {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
{% endblock %}

{% block content %}
    <h2 class="section-title">基金评估结果</h2>

    <!-- 筛选区域 -->
    <div class="filter-container">
        <div class="filter-group">
            <label for="strategy-filter">策略类型:</label>
            <select id="strategy-filter">
                <option value="dca">定投策略</option>
                <option value="ma" selected>均值策略</option>
                <option value="drop">跌幅策略</option>
            </select>
        </div>

        <div class="filter-group" id="ma-range-filter" style="display:none;">
            <label for="ma-range">MA Range:</label>
            <select id="ma-range">
                <option value="30" selected>30 days</option>
                <option value="60">60 days</option>
                <option value="90">90 days</option>
            </select>
        </div>

        <div class="filter-group">
            <label>是否建议买入:</label>
            <label>
                <input type="checkbox" id="buy-yes" checked> 是
            </label>
            <label>
                <input type="checkbox" id="buy-no" checked> 否
            </label>
        </div>

        <div class="filter-group">
            <button id="trigger-eval" class="btn eval-btn">立即评估</button>
        </div>
    </div>

    <!-- 结果表格 -->
    <table class="result-table" id="result-table">
        <thead>
            <tr>
                <th data-sort="fund_code">基金代码 <span class="sort-indicator"></span></th>
                <th>基金名称</th>
                <th data-sort="should_buy">是否建议买入 <span class="sort-indicator"></span></th>
                <th data-sort="annual_return">年化收益率(%) <span class="sort-indicator"></span></th>
                <th>买入次数</th>
            </tr>
        </thead>
        <tbody id="result-tbody"> <!-- 核心修改2：给tbody加id，方便事件委托 -->
            <tr><td colspan="5" class="empty-state">加载中，请稍候...</td></tr>
        </tbody>
    </table>
{% endblock %}

{% block extra_js %}
    <script>
        // 全局变量存储原始数据
        let allResults = [];
        let sortState = {
            fund_code: null,
            should_buy: null,
            annual_return: null
        };

        // 手动触发评估的函数
        async function triggerEvaluation() {
            const triggerBtn = document.getElementById('trigger-eval');
            triggerBtn.disabled = true;
            triggerBtn.textContent = '评估中...';
            try {
                const response = await fetch('/api/trigger-evaluation', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                const result = await response.json();
                if (result.success) {
                    setTimeout(() => {
                        loadEvaluationResults();
                        triggerBtn.disabled = false;
                        triggerBtn.textContent = '立即评估';
                    }, 5000);
                } else {
                    triggerBtn.disabled = false;
                    triggerBtn.textContent = '立即评估';
                }
            } catch (error) {
                console.error('触发评估失败:', error);
                triggerBtn.disabled = false;
                triggerBtn.textContent = '立即评估';
            }
        }

        // 加载评估结果
        function loadEvaluationResults() {
            const tbody = document.getElementById('result-tbody');
            tbody.innerHTML = '<tr><td colspan="5" class="empty-state">加载中，请稍候...</td></tr>';

            const strategy = document.getElementById('strategy-filter').value;
            let url = `/api/evaluation?strategy=${strategy}`;
            if (strategy === 'ma') {
                const maRange = document.getElementById('ma-range').value;
                url += `&ma_range=${maRange}`;
            }

            fetch(url)
                .then(response => {
                    if (!response.ok) throw new Error('加载失败');
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        tbody.innerHTML = `<tr><td colspan="5" class="empty-state">${data.error}</td></tr>`;
                        return;
                    }
                    allResults = data.results;
                    renderFilteredResults();
                })
                .catch(error => {
                    tbody.innerHTML = `<tr><td colspan="5" class="empty-state">加载失败：${error.message}</td></tr>`;
                });
        }

        // 渲染筛选后的结果
        function renderFilteredResults() {
            const tbody = document.getElementById('result-tbody');
            const showYes = document.getElementById('buy-yes').checked;
            const showNo = document.getElementById('buy-no').checked;

            const filtered = allResults.filter(item => {
                if (item.should_buy && !showYes) return false;
                if (!item.should_buy && !showNo) return false;
                return true;
            });
            const sorted = sortResults([...filtered]);

            if (sorted.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="empty-state">没有符合条件的数据</td></tr>';
                return;
            }

            tbody.innerHTML = '';
            sorted.forEach(item => {
                const row = document.createElement('tr');
                // 核心修改3：给行添加data属性存储基金代码（跳转用）
                row.dataset.fundCode = item.fund_code;
                row.innerHTML = `
                    <td>${item.fund_code}</td>
                    <td>${item.fund_name}</td>
                    <td class="${item.should_buy ? 'buy-yes' : 'buy-no'}">${item.should_buy ? '是' : '否'}</td>
                    <td>${item.annual_return}</td>
                    <td>${item.buy_count}</td>
                `;
                tbody.appendChild(row);
            });

            updateSortIndicators();
        }

        // 排序处理（不变）
        function sortResults(results) {
            const sortField = Object.keys(sortState).find(key => sortState[key] !== null);
            if (!sortField) return results;
            return [...results].sort((a, b) => {
                switch (sortField) {
                    case 'fund_code':
                        return sortState[sortField] === 'asc'
                            ? a.fund_code.localeCompare(b.fund_code)
                            : b.fund_code.localeCompare(a.fund_code);
                    case 'should_buy':
                        const valA = a.should_buy ? 1 : 0;
                        const valB = b.should_buy ? 1 : 0;
                        return sortState[sortField] === 'asc' ? valB - valA : valA - valB;
                    case 'annual_return':
                        return sortState[sortField] === 'asc'
                            ? parseFloat(a.annual_return) - parseFloat(b.annual_return)
                            : parseFloat(b.annual_return) - parseFloat(a.annual_return);
                    default:
                        return 0;
                }
            });
        }

        // 更新排序指示器（不变）
        function updateSortIndicators() {
            document.querySelectorAll('.sort-indicator').forEach(el => el.textContent = '');
            const sortField = Object.keys(sortState).find(key => sortState[key] !== null);
            if (sortField) {
                const indicator = document.querySelector(`th[data-sort="${sortField}"] .sort-indicator`);
                indicator.textContent = sortState[sortField] === 'asc' ? '↑' : '↓';
            }
        }

        // 核心修改4：事件委托（给tbody绑定点击事件，处理所有行的跳转）
        document.getElementById('result-tbody').addEventListener('click', function(e) {
            // 1. 找到点击的表格行（tr）
            const tr = e.target.closest('tr');
            if (!tr) return; // 没点到行，直接返回

            // 2. 排除空状态行（不跳转）
            if (tr.querySelector('.empty-state')) return;

            // 3. 排除表头行（不跳转，表头点击仍执行排序）
            if (tr.parentElement.tagName === 'THEAD') return;

            // 4. 获取基金代码，跳转图表页面
            const fundCode = tr.dataset.fundCode;
            if (fundCode) {
                window.location.href = `/fund/chart/${fundCode}`;
            }
        });

        // 原有事件绑定（不变）
        document.querySelectorAll('th[data-sort]').forEach(th => {
            th.addEventListener('click', () => {
                const field = th.getAttribute('data-sort');
                if (sortState[field] === 'asc') {
                    sortState[field] = 'desc';
                } else {
                    Object.keys(sortState).forEach(key => sortState[key] = null);
                    sortState[field] = 'asc';
                }
                renderFilteredResults();
            });
        });
        document.getElementById('buy-yes').addEventListener('change', renderFilteredResults);
        document.getElementById('buy-no').addEventListener('change', renderFilteredResults);
        document.getElementById('strategy-filter').addEventListener('change', function() {
            const maRangeFilter = document.getElementById('ma-range-filter');
            maRangeFilter.style.display = this.value === 'ma' ? 'flex' : 'none';
            loadEvaluationResults();
        });
        document.getElementById('ma-range').addEventListener('change', function() {
            if (document.getElementById('strategy-filter').value === 'ma') {
                loadEvaluationResults();
            }
        });
        document.getElementById('trigger-eval').addEventListener('click', triggerEvaluation);

        // 初始加载
        document.getElementById('strategy-filter').dispatchEvent(new Event('change'));
    </script>
{% endblock %}